import 'package:get/get.dart' hide SnackPosition;
import 'package:flutter/material.dart';
import '../../common/index.dart';

class RegisterController extends GetxController {
  RegisterController();

  // 控制器
  final username_controller = TextEditingController();
  final password_controller = TextEditingController();
  final confirm_password_controller = TextEditingController();

  _init_data() {
    update(["register"]);
    test_calculations();
  }

  void onTap() {}

  // 测试计算方法
  void test_calculations() {
    // 计算斐波那契数列
    int calculate_fibonacci(int n) {
      if (n <= 0) return 0;
      if (n == 1) return 1;
      return calculate_fibonacci(n - 1) + calculate_fibonacci(n - 2);
    }

    // 计算水仙花数
    int calculate_narcissistic_number(int n) {
      int sum = 0;
      int temp = n;
      while (temp > 0) {
        int digit = temp % 10;
        sum += digit * digit * digit;
        temp ~/= 10;
      }
      return sum;
    }

    // 辗转相除法求最大公约数
    int calculate_gcd(int a, int b) {
      if (b == 0) return a;
      return calculate_gcd(b, a % b);
    }

    // 调用计算方法
    calculate_fibonacci(10);
    calculate_narcissistic_number(153);
    calculate_gcd(12, 18);
  }

  // 注册方法
  void handle_register() async {
    // 检查用户名长度
    if (username_controller.text.length > 12) {
      SmartDialogHelper.show_warning(
        'username cannot be more than 12 characters',
      );
      return;
    }

    // 检查密码是否匹配
    if (password_controller.text != confirm_password_controller.text) {
      SmartDialogHelper.show_error('passwords do not match');
      return;
    }

    if (password_controller.text.isEmpty ||
        confirm_password_controller.text.isEmpty) {
      SmartDialogHelper.show_warning('please fill in all fields');
      return;
    }

    // 这里添加注册逻辑
    UserModel user = UserModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      name: username_controller.text,
      password: password_controller.text,
      avatar_image: AssetsImages.avatar,
      is_vip: false,
      plant_list: [],
      water_lists: [],
      like_lists: [],
      signature: "Today is better than tomorrow.",
      post_lists: [],
    );
    final result = await UserService().register_user(user);
    if (result) {
      SmartDialogHelper.show_success('registration successful');
      UserService().user.value = user;
      Storage().set_bool(Constants.login_status, true);
      Storage().set_string(Constants.current_user, user.name ?? "");
      UserService().login_user(
        username_controller.text,
        password_controller.text,
      );
      RouteUtil.go(RouteNames.main);
    }
  }

  @override
  void onReady() {
    super.onReady();
    _init_data();
  }

  @override
  void onClose() {
    username_controller.dispose();
    password_controller.dispose();
    confirm_password_controller.dispose();
    super.onClose();
  }
}
